package com.example.coursehub.course.repository;

import com.example.coursehub.course.entity.Material;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 教学资料数据访问层
 */
@Repository
public interface MaterialRepository extends JpaRepository<Material, String> {

    /**
     * 根据课程ID查询资料
     */
    @Query("SELECT m FROM Material m WHERE m.course.courseId = :courseId ORDER BY m.createdAt DESC")
    List<Material> findByCourseId(@Param("courseId") String courseId);

    /**
     * 根据章节ID查询资料
     */
    @Query("SELECT m FROM Material m WHERE m.chapter.chapterId = :chapterId ORDER BY m.createdAt DESC")
    List<Material> findByChapterId(@Param("chapterId") String chapterId);

    /**
     * 根据课程ID和章节ID查询资料
     */
    @Query("SELECT m FROM Material m WHERE m.course.courseId = :courseId AND m.chapter.chapterId = :chapterId ORDER BY m.createdAt DESC")
    List<Material> findByCourseIdAndChapterId(@Param("courseId") String courseId, @Param("chapterId") String chapterId);

    /**
     * 根据资料名称模糊查询
     */
    List<Material> findByMaterialNameContaining(String materialName);

    /**
     * 根据资料标签查询
     */
    List<Material> findByMaterialLabel(String materialLabel);

    /**
     * 根据文件类型查询
     */
    List<Material> findByFileType(String fileType);

    /**
     * 根据上传者ID查询资料
     */
    List<Material> findByUploaderId(String uploaderId);

    /**
     * 根据状态查询资料
     */
    List<Material> findByStatus(Integer status);

    /**
     * 统计课程的资料数量
     */
    @Query("SELECT COUNT(m) FROM Material m WHERE m.course.courseId = :courseId")
    Long countByCourseId(@Param("courseId") String courseId);

    /**
     * 统计章节的资料数量
     */
    @Query("SELECT COUNT(m) FROM Material m WHERE m.chapter.chapterId = :chapterId")
    Long countByChapterId(@Param("chapterId") String chapterId);

    /**
     * 根据课程ID批量删除资料
     */
    void deleteByCourse_CourseId(String courseId);

    /**
     * 根据章节ID批量删除资料
     */
    void deleteByChapter_ChapterId(String chapterId);

    /**
     * 查询最近上传的资料
     */
    @Query("SELECT m FROM Material m WHERE m.status = 1 ORDER BY m.createdAt DESC")
    List<Material> findRecentMaterials();
}